//------------------------------------------------------------------------------
//SFWK Framework
//Copyright (C) 2011 SQLI

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------

using System;
using System.Data;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Collections.Generic;

namespace SFWK.Core
{
    /// <summary>
    /// Class used to provide static methods for http stuff handling
    /// </summary>
    public static class HTTPHelper
    {
        
        /// <summary>
        /// Returns the http content type corresponding to the file extension passed in parameter
        /// </summary>
        /// <param name="fileExtension">file extension to convert (.doc, .xls, etc...)</param>
        /// <returns>ContentType</returns>
        public static string GetContentType(string fileExtension)
        {
            switch (fileExtension.ToLower().Trim('.'))
            {
                case "doc": { return "application/msword"; }
                case "xls": { return "application/vnd.xls"; }
                case "csv": { return "application/csv-tab-delimited-table"; }
                case "html": 
                case "htm": { return "text/html"; }
                case "bmp": { return "image/bmp"; }
                case "gif": { return "image/gif"; }
                case "jpeg": { return "image/jpeg"; }
                case "png": { return "image/png"; }
                case "tiff": { return "image/tiff"; }
                case "icon": { return "image/vnd.microsoft.icon"; }
                case "wmf": { return "image/wmf"; } 
            }
            return null;
        }

        /// <summary>
        /// Write binary data to http output stream to open binary file in web page
        /// </summary>
        /// <param name="response">HttpResponse</param>
        /// <param name="fileName">Name of the file</param>
        /// <param name="contentType">contentType to display</param>
        /// <param name="data">data to write in the http stream</param>
        public static void WriteFileToHttpOutputStream(System.Web.HttpResponse response, string contentType, byte[] data)
        {
            response.ClearContent();
            response.ContentType = contentType;
            response.BinaryWrite(data);
            response.Flush();
            response.Close();
        }
        /// <summary>
        /// write a csv file and open it in a web page.
        /// </summary>
        /// <param name="response">HttpResponse</param>
        /// <param name="csvFile">string content csv file data</param>
        /// <param name="fileName">generated file name</param>
        public static void WriteFileToHttpOutputStream(System.Web.HttpResponse response, string data, string fileName)
        {
            response.Clear();
            response.Charset = "";
            response.ContentType = GetContentType(fileName.Substring(fileName.LastIndexOf('.')));
            response.AppendHeader("Content-disposition", "filename=" + fileName); //" + DateTime.Now.ToString() + "
            response.Write(data);
            response.Flush();
            response.Close();
        }

        /// <summary>
        /// Force user re-authentication to the navigator and abandon the session
        /// MANTIS-0000633 : LOGOUT does not work
        /// </summary>
        /// <param name="page"></param>
        public static void ForceAuthentication(System.Web.UI.Page page)
        {
            page.Response.Clear();
            page.Response.ClearHeaders();
            page.Response.Status = "401 Unauthorized";
            page.Response.AddHeader("WWW-Authenticate", "Negotiate");
            page.Response.AddHeader("HTTP/1.0 401 ", "NTLM");
            page.Session.Abandon();
        }


        public static Byte[] GetBinaryHttpPostedFileContent(HttpPostedFile postedFile)
        {
            Byte[] fileContent = new byte[postedFile.InputStream.Length];
            postedFile.InputStream.Read(fileContent, 0, Convert.ToInt32(postedFile.InputStream.Length));
            return fileContent;
        }


        public static string SendFile(string url, string paramName, byte[] fileContent, string contentType)
        {
            string res = "";
            WebRequest request = WebRequest.Create(url);
            request.Timeout = 360000; // 6 minutes in milliseconds.      
            request.Method = WebRequestMethods.Http.Post;
            request.ContentLength = 0;
            request.ContentType = contentType;


            // Sends request
            byte[] data = fileContent;
            request.ContentLength = data.Length;
            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            //Gets response
            WebResponse response = request.GetResponse();
            Stream streamResponse = response.GetResponseStream();


            StreamReader readStream = new StreamReader(streamResponse, true);

            Char[] read = new Char[256];
            // Reads 256 characters at a time.    
            int count = readStream.Read(read, 0, 256);
            
            while (count > 0)
            {
                // Dumps the 256 characters on a string and displays the string to the console.
                String str = new String(read, 0, count);
                res += str;
                count = readStream.Read(read, 0, 256);
            }

            response.Close();
            // Releases the resources of the Stream.
            readStream.Close();

            return res;
        }


        /// <summary>
        /// Send an http request passing an argument
        /// </summary>
        /// <param name="url">Url to call</param>
        /// <param name="paramName">argument name</param>
        /// <param name="paramValue">argument value</param>
        /// <returns></returns>
        public static Byte[] CallHttpRequest(string url, string paramName, string paramValue, string contentType)
        {
            WebRequest request = WebRequest.Create(url);
            request.Timeout = 360000; // 6 minutes in milliseconds.      
            request.Method = WebRequestMethods.Http.Post;
            request.ContentLength = 0;
            request.ContentType = contentType;


            // Sends request
            string postData = paramName + "=" + paramValue;
            byte[] data = Encoding.Default.GetBytes(postData);//Modif encoding de utf8 en default pour corriger probleme affichage dans gyroflux 13/02/2009
            request.ContentLength = data.Length;
            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            //Gets response
            WebResponse response = request.GetResponse();
            Stream streamResponse = response.GetResponseStream();
            Byte[] res = _streamToByteArray(streamResponse);
            return res;
        }


        /// <summary>
        /// This method takes a stream and converts it to a byte array.
        /// </summary>
        /// <param name="stream">stream to be converted</param>
        /// <returns>converted byte array</returns>
        private static Byte[] _streamToByteArray(Stream stream)
        {
            List<byte> list = new List<byte>();
            Byte[] buffer = new byte[2048];
            int totalSize = 0;

            // Reads the stream
            BinaryReader reader = new BinaryReader(stream);
            int count = reader.Read(buffer, 0, 2048);
            while (count > 0)
            {
                totalSize += count;

                // Sets the array into a dynamic sized list
                for (int i = 0; i < count; i++)
                {
                    list.Add(buffer[i]);
                }
                count = reader.Read(buffer, 0, 2048);
            }
            reader.Close();

            //sets back values from dynamic list to a static byte array
            Byte[] resultArray = new Byte[list.Count];
            for (int j = 0; j < list.Count; j++)
            {
                resultArray[j] = list[j];
            }
            return resultArray;
        }
    }
}

